package madixin.t21;

class Solution {
    /**
     * 递归
     */
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        if (l1.val < l2.val) {
            l1.next = mergeTwoLists(l1.next, l2);
            return l1;
        } else {
            l2.next = mergeTwoLists(l1, l2.next);
            return l2;
        }
    }

    /**
     * 非递归
     */
    public ListNode mergeTwoLists1(ListNode l1, ListNode l2) {

        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }

        ListNode mergedLists = null;
        ListNode mergedListsCur = null;

        if (l1.val <= l2.val) {
            mergedLists = l1;
            mergedListsCur = l1;
            l1 = l1.next;

        } else {
            mergedLists = l2;
            mergedListsCur = l2;
            l2 = l2.next;
        }

        while (l1 != null || l2 != null) {
            if (l1 == null) {
                mergedListsCur.next = l2;
                break;
            } else if (l2 == null) {
                mergedListsCur.next = l1;
                break;
            } else if (l1.val <= l2.val) {
                mergedListsCur.next = l1;
                mergedListsCur = l1;
                l1 = l1.next;
            } else {
                mergedListsCur.next = l2;
                mergedListsCur = l2;
                l2 = l2.next;
            }
        }

        return mergedLists;
    }
}